package ltd.dujiabao.capability.domain.rulemng.expression;

import static ltd.dujiabao.capability.common.dto.ErrorCodes.SYSTEM_INTERNAL_ERROR;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import ltd.dujiabao.capability.common.exception.BusinessException;

/**
 * @author : DuJiabao
 * @Project : ddd-capability
 * @Time : 2024/4/13 17:35
 * @Desc :
 */
@Component
public class ExpressionFactory {
    public Expression build(String module, String expression) {
        List<String> list = Arrays.stream(expression.split(" "))
                .filter(s -> !StringUtils.isEmpty(s))
                .collect(Collectors.toList());
        if (list.size() != 3) {
            throw new BusinessException(SYSTEM_INTERNAL_ERROR.getCode());
        }
        String key = list.get(0);
        ExpressionType expressionType = ExpressionType.parse(list.get(1));
        String value = list.get(2);

        try {
            Constructor<? extends Expression> constructor = expressionType.getExpressionClass()
                    .getConstructor(String.class, String.class, ExpressionType.class, String.class);
            return constructor.newInstance(module, key, expressionType, value);
        } catch (NoSuchMethodException | InstantiationException | IllegalAccessException |
                 InvocationTargetException e) {
            throw new BusinessException(e, SYSTEM_INTERNAL_ERROR.getCode());
        }
    }
}
